package com.wuhanpe.leafid.model

import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReadWriteLock
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.Volatile

/**
 * @author zooy
 * @since 2025/9/12-16:25
 */
class SegmentBuffer {

    var key: String? = null

    var segments: Array<Segment> = arrayOf()

    @Volatile
    var currentPos: Int = 0

    @Volatile
    var nextReady: Boolean = false

    @Volatile
    var initOk: Boolean = false

    var threadRunning: AtomicBoolean = AtomicBoolean(false)

    var lock: ReadWriteLock = ReentrantReadWriteLock();

    @Volatile
    var step: Int = 0

    @Volatile
    var minStep: Int = 0

    @Volatile
    var updateTimestamp: Long = 0

    constructor() {
        segments = arrayOf(Segment(this), Segment(this))
        currentPos = 0
        nextReady = false
        initOk = false
        threadRunning = AtomicBoolean(false)
        lock = ReentrantReadWriteLock()
    }

    fun nextPos(): Int {
        return (currentPos + 1) % 2
    }

    fun getCurrent(): Segment {
        return segments[currentPos]
    }

    fun rLock(): Lock {
        return lock.readLock()
    }

    fun wLock(): Lock {
        return lock.writeLock()
    }

    fun switchPos() {
        currentPos = nextPos()
    }
}
